const fs = require('fs');
const path = require('path');
const sharp = require('sharp');
const Jimp = require('jimp');

const ICON_DIR = path.join(__dirname, 'static/tabbar');
const ACTIVE_SUFFIX = '-active.png';
const MAIN_COLOR = '#283b66';

async function processIcon(file) {
  const inputPath = path.join(ICON_DIR, file);
  const outputPath = path.join(ICON_DIR, file.replace('.png', ACTIVE_SUFFIX));

  // 1. 用 sharp 叠加主色
  let buffer = await sharp(inputPath)
    .tint(MAIN_COLOR)
    .toBuffer();

  // 2. 用 jimp 加描边和发光
  const image = await Jimp.read(buffer);
  const w = image.bitmap.width;
  const h = image.bitmap.height;

  // 加描边
  const strokeColor = Jimp.cssColorToHex(MAIN_COLOR);
  const strokeWidth = Math.max(2, Math.floor(Math.min(w, h) * 0.08));
  for (let i = -strokeWidth; i <= strokeWidth; i++) {
    for (let j = -strokeWidth; j <= strokeWidth; j++) {
      if (i * i + j * j <= strokeWidth * strokeWidth) {
        image.scan(0, 0, w, h, function (x, y, idx) {
          if (image.bitmap.data[idx + 3] > 0) {
            const nx = x + i, ny = y + j;
            if (nx >= 0 && nx < w && ny >= 0 && ny < h) {
              const nidx = (w * ny + nx) << 2;
              if (image.bitmap.data[nidx + 3] === 0) {
                image.bitmap.data[nidx + 0] = (strokeColor >> 16) & 0xff;
                image.bitmap.data[nidx + 1] = (strokeColor >> 8) & 0xff;
                image.bitmap.data[nidx + 2] = strokeColor & 0xff;
                image.bitmap.data[nidx + 3] = 255;
              }
            }
          }
        });
      }
    }
  }

  // 加发光
  const glow = image.clone().blur(8);
  glow.scan(0, 0, w, h, function (x, y, idx) {
    if (glow.bitmap.data[idx + 3] > 0) {
      glow.bitmap.data[idx + 0] = (strokeColor >> 16) & 0xff;
      glow.bitmap.data[idx + 1] = (strokeColor >> 8) & 0xff;
      glow.bitmap.data[idx + 2] = strokeColor & 0xff;
      glow.bitmap.data[idx + 3] = 120;
    }
  });
  glow.composite(image, 0, 0);

  await glow.writeAsync(outputPath);
  console.log('生成:', outputPath);
}

fs.readdirSync(ICON_DIR)
  .filter(f => f.endsWith('.png') && !f.endsWith(ACTIVE_SUFFIX))
  .forEach(f => processIcon(f));